/*
 * Copyrignt (c) xuzeshui.com. All Rights Reserved.
 * Author: Zeshui Xu<i@xuzeshui.com>
 * Created Time: 2016-05-21 21:46:32
 * Last Modified: 2016-05-22 14:29:39
 * File Name: fxlsx/fxlsx.go
 * Description:
 */
package fxlsx

import (
	"fmt"
	"os"
	"path/filepath"
	"time"

	"github.com/astaxie/beego"
)

var (
	xlsxSaveBaseDir    string
	xlsxSaveHistoryDay int
	xlsxHTTPPrefix     string
)

//获取xlsx保存的目录
func GetXLSXSaveBaseDir() string {
	return xlsxSaveBaseDir
}

//获取xlsx保存的文件路径和对应的url
func GetXLSXFilePath(sessionid string) (string, string) {
	day := time.Now().Format("2006-01-02")
	filename := sessionid + "_" + time.Now().Format("20060102150405.xlsx")
	filePath := filepath.Join(xlsxSaveBaseDir, day, filename)
	urlPath := fmt.Sprintf("%s/%s/%s", xlsxHTTPPrefix, day, filename)
	dirs := filepath.Dir(filePath)
	if _, err := os.Stat(dirs); err != nil {
		os.MkdirAll(dirs, 0755)
	}
	return filePath, urlPath
}

func removeHistoryFile() {
	for {
		select {
		case <-time.After(time.Hour):
			day := time.Now().AddDate(0, 0, -xlsxSaveHistoryDay).Format("2006-01-02")
			dirs := filepath.Join(xlsxSaveBaseDir, day)
			os.RemoveAll(dirs)
		}
	}
}

func init() {
	xlsxSaveBaseDir = beego.AppConfig.DefaultString("xlsx_save_base_dir", "../xlsx")
	xlsxSaveHistoryDay = beego.AppConfig.DefaultInt("xlsx_save_history_day", 1)
	xlsxHTTPPrefix = beego.AppConfig.DefaultString("xlsx_http_prefix", "http://oc.app.qkier.com/xlsx")
	go removeHistoryFile()
}
